﻿#pragma once

#include <QWidget>
#include <QComboBox>
#include <QSpinBox>
#include <QtCharts>
#include <QChart>
#include <QChartView>



class CustomChartView : public QChartView {
public:
    CustomChartView(QChart* chart, QWidget* parent = nullptr) : QChartView(chart, parent) {
        m_legend = chart->legend();
        m_draggingLegend = false;
    }

protected:
    void mousePressEvent(QMouseEvent* event) override {
        if (event->button() == Qt::LeftButton) {
            if (m_legend->isVisible() && m_legend->rect().contains(event->pos())) {
                m_draggingLegend = true;
                m_dragStartPosition = event->pos();
            }
        }
        QChartView::mousePressEvent(event);
    }

    void mouseMoveEvent(QMouseEvent* event) override {
        if (m_draggingLegend) {
            QPoint delta = event->pos() - m_dragStartPosition;
            QPointF newPos = m_legend->pos() + delta;
            m_legend->setPos(newPos);
            m_dragStartPosition = event->pos();
        }
        QChartView::mouseMoveEvent(event);
    }

    void mouseReleaseEvent(QMouseEvent* event) override {
        if (event->button() == Qt::LeftButton) {
            m_draggingLegend = false;
        }
        QChartView::mouseReleaseEvent(event);
    }

private:
    QLegend* m_legend;
    bool m_draggingLegend;
    QPoint m_dragStartPosition;
};

class HistogramWidget  : public QWidget
{
	Q_OBJECT

public:
	HistogramWidget(const QVector<QVector<double>>& columnData, const QStringList& columnNames, QWidget* parent = nullptr);
	~HistogramWidget();



private slots:
	void onColumnSelected(int index);
	void onDecimalNumChanged(int decimalNum);
	void onLineNumChanged(int lineNum);
    void onFontSizeChanged(int fontsize);
    void onBinNumChanged(int binNum);
    void onNormalizeChecked(int state);

private:
	void initUI();
	void updateChart();
	void calculateStatistics(int columnIndex, double& vmin, double& vmax, double& vmean, double& vvar);
	void drawHistogram(int columnIndex, const QString& title);

private:
	QComboBox* cmbColumn;
	QSpinBox* spbLineNum, *spbBinNum, * spbDecimalNum, *spbFontSize;
    QCheckBox* chkNormalize;
    QChart* chart;
	const QVector<QVector<double>> & columnData;
	const QStringList& columnNames;
};
